<template>
  <div>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog v-model="open" :title="title" :close-on-click-modal='false' width="750px" append-to-body>
	
	  <el-form ref="menuFormRef" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="24">
		  <el-col :span="24">
            <el-form-item label="父菜单" prop="parentId">
              <el-select v-model="form.parentId" :disabled="parentIdDisabled" placeholder="父菜单" :popper-append-to-body="false" style="width: 100%">
				<el-option v-for="item in parentMenuList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>	
		  <el-col :span="24">
            <el-form-item label="菜单名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入菜单名称" />
            </el-form-item>
          </el-col>
		  <el-col :span="24">
            <el-form-item label="菜单类型" prop="type">
              <el-select v-model="form.type" placeholder="菜单类型" :disabled="form.id != ''" :popper-append-to-body="false" style="width: 100%">
				<el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="路由" prop="route">
              <el-input v-model="form.route" placeholder="路由" />
            </el-form-item>
          </el-col>
          <el-col :span="24" v-show="false">
            <el-form-item label="图标" prop="icon">
              <el-input v-model="form.icon" placeholder="请选择图标" suffix-icon="el-icon-arrow-down"/>
            </el-form-item>
          </el-col>
		  <el-col :span="24">
            <el-form-item label="图标" prop="icon">
			
			  <el-input v-model="selectedIcon" placeholder="选择图标" readonly>
				<template #suffix>
				  <el-icon class="el-input__icon" @click="openIconPicker">
					<component :is="selectedIcon || 'Search'" />
				  </el-icon>
				</template>
			  </el-input>

            </el-form-item>
          </el-col>
		  <el-col :span="24">
            <el-form-item label="链接类型" prop="linkType">
              <el-select v-model="form.linkType" placeholder="链接类型" :disabled="form.type != 5" :popper-append-to-body="false" style="width: 100%">
				<el-option v-for="item in linkTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="权限标识" prop="perms">
              <el-input v-model="form.perms" placeholder="请输入权限标识" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="路径" prop="url">
              <el-input v-model="form.url" placeholder="请输入路径" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form.sort" placeholder="请输入排序" style="width: 100%"/>
            </el-form-item>
          </el-col> 	  
        </el-row>
		
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="open = false">取 消</el-button>
        </div>
      </template>
	 
    </el-dialog>
	
	<!-- 图标选择弹窗 -->
	  <el-dialog v-model="dialogVisible" title="选择图标" width="60%">
		<div class="icon-list">
		  <div 
			v-for="(icon, name) in icons" 
			:key="name" 
			class="icon-item"
			@click="selectIcon(name)"
		  >
			<el-icon :size="24">
			  <component :is="icon" />
			</el-icon>
			<span>{{ name }}</span>
		  </div>
		</div>
	  </el-dialog>
	  
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, nextTick, toRef, computed } from "vue";
import baseService from "@/service/baseService";
import { ElMessage, ElMessageBox} from "element-plus";
import * as icons from '@element-plus/icons-vue'; // 导入所有图标‌:ml-citation{ref="3,4" data="citationList"}
import { Search } from '@element-plus/icons-vue';

defineOptions({
  name: 'iconSelect',
});

// 表单实例
const menuFormRef = ref();
// 是否打开弹出框
const open = ref(false);
// 父id是否禁用
const parentIdDisabled = ref(true);
// 弹出框标题
const title = ref("");

// 提交表单数据
let form = toRef(
  reactive({
    id: "",
    name: "",
    route: "",
    type: "",
    parentId: "",
	linkType: "",
	perms: "",
	icon: "",
	url: "",
	sort: ""
  })
);
// 表单验证
const rules = ref({
  parentId: [{ required: true, message: "父菜单不能为空", trigger: "blur" }],
  name: [{ required: true, message: "菜单名称不能为空", trigger: "blur" }],
  type: [{ required: true, message: "菜单类型不能为空", trigger: "blur" }],
  perms: [{ required: true, message: "权限标识不能为空", trigger: "blur" }],
  sort: [{ required: true, message: "排序不能为空", trigger: "blur" }]
});

// 图标集合
const iconNames = ref<any[]>();

//父级菜单列表
const parentMenuList = ref<any[]>();

//定义菜单类型
const typeOptions = [
  { value: 1, label: '目录' },
  { value: 2, label: '菜单' }, 
  { value: 3, label: 'tab页' },
  { value: 4, label: '按钮' },
  { value: 5, label: '超链接' },
  { value: 6, label: '后台接口' },
  { value: 7, label: '其他' }
];

//定义链接类型
const linkTypeOptions = [
  { value: 1, label: '无' },
  { value: 2, label: '内嵌' }, 
  { value: 3, label: '外链' }
];

const emit = defineEmits(["callBack"]);//声明事件(父级页面上添加的 @监听事件)

//父调子的子
const addFormShow = (titleName: string, parentId:string) => {   
  open.value = true;
  title.value = titleName; 
  form.value = {
    id: "",
    name: "",
    route: "",
    type: "",
    parentId: "",
	linkType: 1,
	perms: "",
	icon: "",
	url: "",
	sort: 1
  };
  parentIdDisabled.value = false;
  form.value.parentId = parentId;
  form.value.icon = 'Search';
  parentIdDisabled.value = true;
  selectedIcon.value = form.value.icon;
};

/**
 * 表单重置
 */
function reset() {
  form.value = {
    id: "",
    name: "",
    route: "",
    type: "",
    parentId: "",
	linkType: 1,
	perms: "",
	icon: "",
	url: "",
	sort: 1
  };

  nextTick(() => {
    menuFormRef.value?.resetFields();
  });
}

//定义类型
interface Menu {
  id: string
  name: string
  route: string
  type: number
  parentId: string
  linkType: number
  perms: string
  icon: string
  url: string
  sort: number
};

//父调子的子
const updateFormShow = (titleName: string, row: Menu) => {
  open.value = true;
  title.value = titleName; 
  reset();
  baseService.get(`/system/menu/info/${row.id}`).then((res) => {
    if (res.code === 200) {
      form.value = res.data;
	  selectedIcon.value = form.value.icon;
    }
  }); 
};
  
/**
 * 提交按钮
 */
const submitForm = async() => {
  menuFormRef.value.validate((valid: boolean) => {
    if (!valid) return;
    baseService.post(`/system/menu/save`, form.value).then((res) => {
      if (res.code === 200) {
        ElMessage.success(res.msg);
        open.value = false;
        emit("callBack");
      } else {
        ElMessage.error(res.msg);
      }
    });
  });
};

/**
 * 查询父级菜单列表
 */
const getParentMenuList = () => {
  baseService.get("/system/menu/parentMenuList").then((res) => {
    if (res.code === 200) {
      parentMenuList.value = res.data;
    }
  });
};

defineExpose({
  addFormShow,
  updateFormShow
}) //将子组件方法暴露出来，让父组件调用

getParentMenuList();

const selectedIcon = ref(''); // 当前选中图标名
const dialogVisible = ref(false); // 控制弹窗显示

// 打开图标选择弹窗
const openIconPicker = () => {
  dialogVisible.value = true;
};

// 选择图标并更新输入框
const selectIcon = (iconName) => {
  selectedIcon.value = iconName;
  form.value.icon = iconName;
  dialogVisible.value = false;
};

</script>

<style scoped>

.el-input__icon {
  cursor: pointer;
}

.icon-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 16px;
}
.icon-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}
.icon-item:hover {
  background-color: var(--el-color-primary-light-9);
}

</style>
